package cn.autumnorange.app.user.provider.service;

import cn.autumnorange.app.common.dto.ResultDto;
import cn.autumnorange.app.user.api.AppUserService;
import cn.autumnorange.app.user.api.dto.UserDetailDto;
import cn.autumnorange.app.user.provider.entity.SysUserEntity;
import cn.autumnorange.app.user.provider.repository.SysUserJpaRepository;
import cn.autumnorange.app.user.provider.repository.SysUserRepository;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Primary
@Service
@Slf4j
public class AppUserServiceImpl implements AppUserService {
  @Autowired private SysUserRepository sysUserRepository;

  @Autowired private SysUserJpaRepository sysUserJpaRepository;

  @Override
  public ResponseEntity<ResultDto<UserDetailDto>> loadUserByUsername(String name) {
    //    SysUserEntity sysUserEntity =
    //        sysUserRepository.getUserByIdCodeEmailMobile("code", StringUtils.trimToNull(name));
    //
    //    UserDetailDto userDetailDto = new UserDetailDto();
    //    BeanUtils.copyProperties(sysUserEntity, userDetailDto, "code");
    //    userDetailDto.setUsername(sysUserEntity.getCode());
    SysUserEntity sysUserEntity = sysUserJpaRepository.findByCodeAndIsDelete(name, false);
    UserDetailDto userDetailDto = new UserDetailDto();
    BeanUtils.copyProperties(sysUserEntity, userDetailDto, "code");
    userDetailDto.setUsername(sysUserEntity.getCode());
    return ResponseEntity.ok(ResultDto.createDataResult(userDetailDto));
  }

  @Override
  public ResponseEntity<ResultDto<UserDetailDto>> loginSuccess() {
    Authentication authorization = SecurityContextHolder.getContext().getAuthentication();
    String authenticationStr= JSONObject.toJSONString(authorization.getDetails());
    UserDetailDto userDetailDto = new UserDetailDto();
    userDetailDto.setUsername(authorization.getName());
    userDetailDto.setPassword(authenticationStr);

    return ResponseEntity.ok(ResultDto.createDataResult(userDetailDto));
  }

  //    @Override
  //    public JsonResult addUpdSysUser(InsertSysUserDto insertSysUserDto) {
  //        return null;
  //    }

}
